package com.xiaolei.fastnio.library.Workers

import com.xiaolei.fastnio.library.Client.Session
import com.xiaolei.fastnio.library.Factorys.IClientAdapterFactory
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel

/**
 * 客户端连接事件的工作线程
 */
class ClientAcceptWorker(
        private val acceptSelector: Selector,
        private val readSelector: Selector,
        private val clientFactory: IClientAdapterFactory<*>
) : Runnable
{
    private inline fun acceptSelectionKey(key: SelectionKey)
    {
        val serverChannel = key.channel() as ServerSocketChannel
        val clientChannel = serverChannel.accept()

        clientChannel.configureBlocking(false)
        // clientChannel.socket().tcpNoDelay = true
        // clientChannel.socket().keepAlive = true
        val session = Session(clientChannel).apply {
            isAlive = true
        }

        // 获取一下客户端的适配器，回调客户端的连接事件
        val clientAdapter = clientFactory.get(session.sessionId)
        clientAdapter.onOpen(session)

        clientChannel.register(readSelector, SelectionKey.OP_READ, session)
        readSelector.wakeup()
    }

    override fun run()
    {
        // 死循环，直到通道关闭
        while (acceptSelector.isOpen)
        {
            // 就绪数量
            val keyCount = acceptSelector.select()
            if (keyCount > 0)
            {
                // 获取就绪
                val iterator = acceptSelector.selectedKeys().iterator()
                while (iterator.hasNext())
                {
                    val key = iterator.next()
                    iterator.remove()
                    if (key.isAcceptable)
                    {
                        acceptSelectionKey(key)
                    }
                }
            }
        }
    }
}